<?php
/**
 * Created by PhpStorm.
 *
 * Author : Traveler.
 * Time   : 2020/2/21 14:24
 * Company: Inner Mongolia Zhengzhi Network Technology Co., Ltd
 */

namespace app\admin\controller;


use app\admin\BaseController;
use app\admin\middleware\Auth;
use app\admin\middleware\Login;
use app\admin\model\Staff as StaffModel;
use think\facade\View;

class Staff extends BaseController
{
    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [
        Auth::class => ['only' => ['add', 'edit', 'status', 'delete', 'resetPassword']],
        Login::class,
    ];

    /**
     * 接口：获取员工列表(表格渲染)
     * @return \think\response\Json
     */
    public function getTableData()
    {
        $param = $this->request->param();
        $data  = StaffModel::getStaffTable($param);

        return $this->success('获取员工列表成功', $data['data'], ['count' => $data['count']]);
    }

    /**
     * 接口：获取员工列表(下拉选择组件渲染)
     * @return \think\response\Json
     */
    public function getValidStaff()
    {
        return $this->success('获取员工列表成功', StaffModel::getValidStaff());
    }

    /**
     * 页面渲染：员工管理
     * @return string
     */
    public function index()
    {
        // 权限标识
        $flag = [
            'add'    => 'staff:add',
            'edit'   => 'staff:edit',
            'status' => 'staff:status',
            'delete' => 'staff:delete',
            'reset'  => 'staff:reset',
        ];

        return View::assign('flag', $flag)->fetch();
    }

    /**
     * 添加员工
     * @return string|\think\response\Json
     */
    public function add()
    {
        // 提交
        if ($this->request->isPost()) {
            $data = $this->request->post();

            // 验证数据
            $validate = $this->validate($data, 'Staff.add');
            if ($validate !== true) {
                return $this->error($validate);
            }

            // 设置默认密码并加密
            $data['password'] = ibms_default_password();

            if (!isset($data['status'])) {
                $data['status'] = 0;
            }

            $result = StaffModel::create($data);
            if (!$result->isEmpty()) {
                return $this->success('添加成功');
            }

            return $this->error('添加失败');
        }

        // 渲染页面：添加员工
        return View::fetch();
    }

    /**
     * 编辑员工
     * @return string|\think\response\Json
     */
    public function edit()
    {
        // 提交
        if ($this->request->isPost()) {
            $data = $this->request->post();

            // 验证数据
            $validate = $this->validate($data, 'Staff.edit');
            if ($validate !== true) {
                return $this->error($validate);
            }

            // 去掉password字段，防止恶意提交密码
            if (isset($data['password'])) {
                unset($data['password']);
            }

            if (!isset($data['status'])) {
                $data['status'] = 0;
            }

            $result = StaffModel::update($data);
            if (!$result->isEmpty()) {
                return $this->success('编辑成功');
            }

            return $this->error('编辑失败');
        }

        // 渲染页面：编辑员工
        return View::fetch();
    }

    /**
     * 批量启用/禁用
     * @return \think\response\Json
     */
    public function status()
    {
        // 提交
        if ($this->request->isPost()) {
            $status = $this->request->post('status') ?: 0;
            $operation = 0 == $status ? '禁用' : '启用';
            $ids = trim($this->request->post('idsStr'), " \t\n\r\0\x0B,");

            $result = StaffModel::whereIn('id', $ids)->update(['status' => $status]);
            if ($result) {
                return $this->success($operation . '成功：' . $result . '条');
            }

            return $this->error($operation . '失败');
        }

        return $this->error('非法请求');
    }

    /**
     * 批量删除
     * @return \think\response\Json
     */
    public function delete()
    {
        // 提交
        if ($this->request->isPost()) {
            $ids = trim($this->request->post('idsStr'), " \t\n\r\0\x0B,");

//            $result = StaffModel::whereIn('id', $ids)->update(['delete_time' => time()]);
            $result = StaffModel::whereIn('id', $ids)->delete();
            if ($result) {
                return $this->success('删除成功：' . $result . '条');
            }

            return $this->error('删除失败');
        }

        return $this->error('非法请求');
    }

    /**
     * 重置密码
     * @return string
     */
    public function resetPassword()
    {
        // 提交
        if ($this->request->isPost()) {
            $ids = trim($this->request->post('idsStr'), " \t\n\r\0\x0B,");

            $result = StaffModel::whereIn('id', $ids)->update(['password' => ibms_default_password()]);
            if ($result) {
                return $this->success('重置密码成功：' . $result . '条');
            }

            return $this->error('重置密码失败');
        }

        // 渲染页面：修改密码
        return $this->error('非法请求');
    }

    /**
     * 修改密码
     * @return string
     */
    public function editPassword()
    {
        // 提交
        if ($this->request->isPost()) {
            $data = $this->request->post();

            // 验证数据
            $validate = $this->validate($data, 'Staff.editpwd');
            if ($validate !== true) {
                return $this->error($validate);
            }

            $staff = StaffModel::find(session('admin_id'));
            if (!$staff) {
                return $this->error('用户不存在');
            }

            if (!ibms_password_verify($data['password'], $staff['password'])) {
                return $this->error('旧密码错误');
            }

            $result = $staff->save(['password' => ibms_password_hash($data['new_password'])]);
            if ($result) {
                return $this->success('密码修改成功');
            }

            return $this->error('密码修改失败');
        }

        // 渲染页面：修改密码
        return View::fetch();
    }
}